package es.usc.citius.servando.calendula.scheduling;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;

import org.jetbrains.annotations.NotNull;

import es.usc.citius.servando.calendula.CalendulaApp;
import es.usc.citius.servando.calendula.util.LogUtil;

public class AlarmIntentService extends JobIntentService {

    private static final String TAG = "AlarmIntentService";

    private static final int JOB_ID = 1;

    public static void enqueueWork(Context context, Intent work) {
        JobIntentService.enqueueWork(context, AlarmIntentService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull @NotNull Intent intent) {
        LogUtil.d(TAG, "Service started");

        // get intent params with alarm info
        AlarmIntentParams params = AlarmScheduler.getAlarmParams(intent);

        if (params == null) {
            LogUtil.w(TAG, "No extra params supplied");
            return;
        }

        LogUtil.d(TAG, "Alarm received: " + params.toString());

        if (params.action != CalendulaApp.ACTION_DAILY_ALARM) {
            try {
                params.date();
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

        }

        switch (params.action) {
            case CalendulaApp.ACTION_ROUTINE_TIME:
            case CalendulaApp.ACTION_ROUTINE_DELAYED_TIME:
                AlarmScheduler.instance().onAlarmReceived(
                        params,
                        getApplicationContext()
                );
                break;
            case CalendulaApp.ACTION_HOURLY_SCHEDULE_TIME:
            case CalendulaApp.ACTION_HOURLY_SCHEDULE_DELAYED_TIME:
                AlarmScheduler.instance().onHourlyAlarmReceived(
                        params,
                        getApplicationContext()
                );
                break;
            case CalendulaApp.ACTION_DAILY_ALARM:
                LogUtil.d(TAG, "Received daily alarm");
                DailyAgenda.instance().setupForToday(getApplicationContext(), false);
                break;
            default:
                LogUtil.w(TAG, "Unknown action received");
                break;
        }
    }
}
